<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use think\Model;

use PHPExcel;
use PHPExcel_IOFactory;
use PHPExcel_Writer_Excel5;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Fill;
use PHPExcel_Style_Border;
use PHPExcel_Cell_DataType;
//岗位
class Job extends Common
{
	public function huishou($page=1,$list=10){
		$where="d.is_actived=1 and d.is_deleted=0 and j.is_actived=0 and j.is_deleted=0 ";
		$sum=Db::table("department")->alias("d")->join("job j","d.id=j.department_id","LEFT")
    	->where($where)->count();
    	$maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;
        $jarr=Db::table("department")->alias("d")->join("job j","d.id=j.department_id","LEFT")->join("job jp","j.parent_id=jp.id","LEFT")
    	->where($where)->order("j.id")->limit("$start,$list")
    	->field("j.id,j.job_no,j.job_name,j.job_title,j.job_level,d.de_name,j.remark,jp.job_name as pjob")->select();
    	 
		$this->assign("page",$page);
		$this->assign("list",$list);
		$this->assign("maxpage",$maxpage);
		$this->assign("sum",$sum);
		$this->assign("jarr",$jarr);
		return $this->fetch('huishou');
	}
	public function jobdc(){
		$where="d.is_actived=1 and d.is_deleted=0 and j.is_actived=1 and j.is_deleted=0 ";
		$jarr=Db::table("department")->alias("d")->join("job j","d.id=j.department_id","LEFT")->join("job jp","j.parent_id=jp.id","LEFT")
    	->where($where)->order("j.id")
    	->field("j.id,j.job_no,j.job_name,j.job_title,j.job_level,d.de_name,j.remark,jp.job_name as pjob")->select();
    	$eid = Session::get("employee_id");
        $users = Db::table("employee")->where(["id" => $eid])->find();

        Vendor("PHPExcel");


        Vendor("PHPExcel.Writer.Excel5");

        // Loader::import('PHPExcel.Classes.PHPExcel');
        //Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
        //  Vendor("Excel.PHPExcel.Writer.Excel2007");
        $objPHPExcel = new PHPExcel();


        $objProps = $objPHPExcel->getProperties();

        $objProps->setCreator('admin');
        $objProps->setLastModifiedBy('admin');
        $objProps->setTitle('Office 2003 XLSX Test Document');
        $objProps->setSubject('Office 2003 XLSX Test Document');
        $objProps->setDescription("Test document, generated by PHPExcel.");
        $objProps->setKeywords("office excel PHPExcel");
        $objProps->setCategory("Test");

        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("岗位列表");

        #################总标题

        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->mergeCells('A1:G1');
        $objPHPExcel->getActiveSheet()->setCellValue('A1', "岗位列表");
        //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(14);
        #################表头信息
        $objPHPExcel->getActiveSheet()->mergeCells('A2:G2');
        $objPHPExcel->getActiveSheet()->setCellValue('A2', "(本表单由软件导出，导出时间：" . date("Y-m-d H:i:s") . "；导出人：{$users["em_name"]})");
        //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(12);
        $objPHPExcel->getActiveSheet()->getStyle('3')->getAlignment()->setWrapText(true);
        
         $objPHPExcel->getActiveSheet()->getStyle('A3:G3')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
         $objPHPExcel->getActiveSheet()->getStyle('A3:G3')->getFill()->getStartColor()->setARGB('0099CCFF');
             //水平剧中
         $objPHPExcel->getActiveSheet()->getStyle('A3:G3')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
         $objPHPExcel->getActiveSheet()->getStyle('A3:G3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

        $objPHPExcel->getActiveSheet()->setCellValue('A3',"序号");
        $objPHPExcel->getActiveSheet()->setCellValue('B3',"岗位编号");
        $objPHPExcel->getActiveSheet()->setCellValue('C3',"岗位名称");
        $objPHPExcel->getActiveSheet()->setCellValue('D3',"对外称谓");
        $objPHPExcel->getActiveSheet()->setCellValue('E3',"岗位等级");
        $objPHPExcel->getActiveSheet()->setCellValue('F3',"上级岗位");
        $objPHPExcel->getActiveSheet()->setCellValue('G3',"所属部门");

        $h=3;
        for($i=0;$i<count($jarr);$i++){
            $h++;
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('A'.$h,$i+1,PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('B'.$h,$jarr[$i]["job_no"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('C'.$h,$jarr[$i]["job_name"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('D'.$h,$jarr[$i]["job_title"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('E'.$h,$jarr[$i]["job_level"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('F'.$h,$jarr[$i]["pjob"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('G'.$h,$jarr[$i]["de_name"],PHPExcel_Cell_DataType::TYPE_STRING);
        }
         $styleArray = array(  
        'borders' => array(  
            'allborders' => array(  
                //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                'style' => PHPExcel_Style_Border::BORDER_THIN,//细边框  
                //'color' => array('argb' => 'FFFF0000'),  
            ),  
        ),  
    );  
            $objPHPExcel->getActiveSheet()->getStyle('A1:G'.$h)->applyFromArray($styleArray);//这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪
        //设置宽度
            $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        //var_dump($objWriter);exit;
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires:0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=file.xls');
        header("Content-type:text/html;charset=utf-8");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
	}
	public function manage($page=1,$list=10){
		$depart_model=model('Department');
		//查询条件
		
    	$where="d.is_actived=1 and d.is_deleted=0 ";

    	$alldepart=Db::table("department")->alias("d")->where($where)->order("index")->field("id,parent_id as pId,de_name as name")->select();
    	$this->assign("alldepart",json_encode($alldepart));

    	//接收数据
    	$request = Request::instance();

    	
    	$data=$request->post();
    	$where="d.is_actived=1 and d.is_deleted=0 and j.is_actived=1 and j.is_deleted=0 ";
    	if($data){
    		if(trim($data["de_name"])){
    			//获取查询部门的编号
    		$datawhere["is_actived"]=1;$datawhere["is_deleted"]=0;$datawhere["de_name"]=trim($data["de_name"]);

    		$thisdipart=$depart_model->get_this_department($datawhere);
    		if($thisdipart){
    			switch ($data['check_type']) {
    			case '1':
    				$where.="and (d.id={$thisdipart["id"]} or d.path like '%[{$thisdipart["id"]}]%') ";
    				
    				break;
    			case '2':
    				$where.="and d.id={$thisdipart["id"]} ";
    				break;
    			case '3':
    				$where.="and d.path like '%[{$thisdipart["id"]}]%' ";
    				break;
    			
    			}
    			
    			}else{
    			$where="1=2";
    			}
    		}
    		if(trim($data["job_name"]))
    			$where.="and j.job_name like '%{$data["job_name"]}%' ";

    	}else{
    		$data=["de_name"=>"","check_type"=>1,"job_name"=>""];
    	}
    	$sum=Db::table("department")->alias("d")->join("job j","d.id=j.department_id","LEFT")
    	->where($where)->count();
    	$maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;
        $jarr=Db::table("department")->alias("d")->join("job j","d.id=j.department_id","LEFT")->join("job jp","j.parent_id=jp.id","LEFT")
    	->where($where)->order("j.id")->limit("$start,$list")
    	->field("j.id,j.job_no,j.job_name,j.job_title,j.job_level,d.de_name,j.remark,jp.job_name as pjob")->select();
    	  $this->assign("data",$data);
		$this->assign("page",$page);
		$this->assign("list",$list);
		$this->assign("maxpage",$maxpage);
		$this->assign("sum",$sum);
		$this->assign("jarr",$jarr);
		return $this->fetch('manage');
	}

	//获取所有岗位
	public function getjobs($jid=0){

		$arr=Db::table("job")->where(["is_actived"=>1,"is_deleted"=>0])
		->field("id,job_name as name,parent_id as pId,path")->select();
		$result=[];
		for($i=0;$i<count($arr);$i++){
			$result[$i]["id"]=$arr[$i]["id"];
			$result[$i]["name"]=$arr[$i]["name"];
			$result[$i]["pId"]=$arr[$i]["pId"];
			  if($arr[$i]["path"]){
                    $tmp=explode('[',$arr[$i]["path"]);
                    $str=implode('',$tmp);
                    $notp=explode("]",$str);
                    //return $arr;
                   // print_r($notp);//exit;
                }else{
                    $notp=[];
                }
                if($result[$i]["id"]==$jid||in_array($jid,$notp)){
                     $result[$i]["chkDisabled"]=true;
                }
		}
		return json_encode($result);
	}
	//查询岗位信息
	public function getthisjob($jid=0){
		$arr=Db::table("department")->alias("d")->join("job j","d.id=j.department_id","LEFT")->join("job jp","j.parent_id=jp.id","LEFT")
    	->where("j.id=$jid")
    	->field("j.id,j.job_no,j.job_name,j.job_title,j.job_level,d.de_name,j.remark,jp.job_name as pjob,jp.id as jpid,d.id as did")->find();
    	return json_encode($arr);
	}
	//修改岗位
	public function update_job(){
		$request = Request::instance();
    	
    	$data=$request->post();//接收数据
    	//print_r($data);exit;
    	if($data){
    		if(trim($data["jid"])){
    			$newdata["id"]=trim($data["jid"]);
	    		$newdata["job_no"]=trim($data["job_no"]);
	    		$newdata["job_name"]=htmlspecialchars(trim($data["job_name"])) ;
	    		$newdata["parent_id"]=trim($data["parent_id"]);
	    		$newdata["job_title"]=htmlspecialchars(trim($data["job_title"])) ;
	    		$newdata["job_level"]=trim($data["job_level"]);
	    		$newdata["department_id"]=trim($data["department_id"]);
	    		$newdata["remark"]=htmlspecialchars(trim($data["remark"])) ;
	    		$newdata["modifiled_on"]=date("Y-m-d H:i:s") ;
	    		//处理path
	    		$newdata["path"]="";
	    		if($newdata["parent_id"]){
	    			//查询上级的path
	    			$pjob=Db::table("job")->where("id={$newdata["parent_id"]}")->find();
	    			$newdata["path"]=$pjob["path"]."[{$newdata["parent_id"]}]";
	    		}
	    		if(!$newdata["job_no"])
	    			return 2;//岗位编号空
	    		if(!$newdata["job_name"])
	    			return 3;//岗位名空
	    		if(!$newdata["job_title"])
	    			return 4;//岗位称谓空
	    		if(!$newdata["job_level"])
	    			return 5;//等级空
	    		if(!$newdata["department_id"])
	    			return 6;//部门空
	    		$is_chongfu=Db::table("job")->where("(job_name='{$newdata["job_name"]}' or job_no='{$newdata["job_no"]}') and id<>{$newdata["id"]}")->count();
	    		if($is_chongfu)
	    			return 8;//重现重复

	    		                   //获取自身原先path
	            $yuan=Db::table("job")->where("id={$newdata["id"]}")->find();
	            $oldpath=$yuan["path"];
	    		 Db::startTrans(); //开启事物
	    		 try{
	    		 	$res1=Db::table("job")->update($newdata);
	    		 	//下级部门path修改
                                $xiaji=Db::table("job")->where("path like '%[{$newdata["id"]}]%'")->select();
                                $check=0;
                                for($i=0;$i<count($xiaji);$i++){
                                    if($oldpath){
                                         $tmparr["path"]=str_replace($oldpath,$newdata["path"],$xiaji[$i]["path"]);
                                     }else{
                                         $tmparr["path"]=$newdata["path"].$xiaji[$i]["path"];
                                     }
                                   
                                    $tmparr["modifiled_on"]=date("Y-m-d H:i:s") ;
                                     $tmparr["id"]=$xiaji[$i]["id"];
                                    $tmpres=Db::table("job")->update($tmparr);
                                    if($tmpres)
                                        $check++;

                                }
                                if($check==count($xiaji))
                                        $res3=1;
                                    else
                                        $res3=0;
	    		 }catch(\Exception $e){
	    		 	  Db::rollBack();
	                  return 7;//失败
	    		 }
	    		 if($res1&&$res3){
	    		 	  Db::commit(); //事物提交
	                  return 1;//成功
	    		 }else{
	    		 	Db::rollBack();
	                  return 7;//失败
	    		 }
    		}else{
    		return 0;
    	}
    		
    	}else{
    		return 0;
    	}
	}
	//删除岗位
	public function dropj(){
		Db::startTrans();
		$request = Request::instance();
        
        $data=$request->post();//接收数据
        //print_r($data);exit;
        //$data["m_users_id"]=Session::get("login_id");
			//$data["modifiled_on"]=date("Y-m-d H:i:s");
		//验证岗位是否有人
		$has=db("employee e")->join("job_employee je","je.employee_id=e.id")->where(["e.is_actived"=>1,"e.is_deleted"=>0,"je.job_id"=>$data["jid"]])->find();
		if($has){
			return json_encode(["msg"=>"该岗位下存在员工，请先行处理","state"=>2]);
		}
		//验证下级岗位
		$hasj=db("job")->where("path like '%[{$data["jid"]}]%' and is_deleted=0 and is_actived=1")->find();
		if($hasj){
			return json_encode(["msg"=>"该岗位尚有下级岗位存在，请先行处理","state"=>2]);
		}
		try{
			$where=["id"=>$data["jid"],"is_actived"=>0,"modifiled_on"=>date("Y-m-d H:i:s")];
			$res=Db::table("job")->update($where);
			db("job_employee")->where(["job_id"=>$data["jid"]])->delete();
		}catch(\Exception $e){
            Db::rollBack();
            return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
        }
		
		Db::commit();
		return json_encode(["msg"=>"","state"=>1]);
	}
	//恢复岗位
	public function huifuj(){
		$request = Request::instance();
        
        $data=$request->post();//接收数据
        //print_r($data);exit;
        //$data["m_users_id"]=Session::get("login_id");
			//$data["modifiled_on"]=date("Y-m-d H:i:s");
		//检测是否有未恢复的上级
		$pid=db("job")->where(["id"=>$data["jid"],"is_actived"=>0,"is_deleted"=>0])->value("parent_id");
		if($pid){
			$has=db("job")->where(["id"=>$pid,"is_actived"=>0,"is_deleted"=>0])->find();
		}else{
			$has=[];
		}
		if($has){
			return json_encode(["msg"=>"存在尚未恢复的上级岗位，请先行处理","state"=>2]);
		}else{
			try{
				$where=["id"=>$data["jid"],"is_actived"=>1,"modifiled_on"=>date("Y-m-d H:i:s")];
				$res=Db::table("job")->update($where);
			}catch(\Exception $e){
				return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
			}
			return json_encode(["msg"=>"","state"=>1]);
		}
		
		
	}
}